package com.bgs.travelapp.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.bgs.travelapp.alipay.service.AlipayService;
import com.bgs.travelapp.order.entity.OrderRealEntity;
import com.bgs.travelapp.order.entity.ScenicOrderEntity;
import com.bgs.travelapp.order.mapper.OrderRealMapper;
import com.bgs.travelapp.order.mapper.PurchaseMapper;
import com.bgs.travelapp.order.service.PurchaseService;
import com.bgs.travelapp.result.CommonResult;
import com.bgs.travelapp.ticket.mapper.TicketMapper;
import com.bgs.travelapp.userRealBinds.entity.UserRealBindsEntity;
import com.bgs.travelapp.util.MailUtils;
import com.bgs.travelapp.util.RanNum;
import com.bgs.travelapp.util.RedisKeyExpirationListener;
import com.bgs.travelapp.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.Map;

import java.util.Map;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Component
@EnableScheduling
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Resource
    PurchaseMapper purchaseMapper;

    @Resource
    TicketMapper ticketMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisKeyExpirationListener redisKeyExpirationListener;

    @Autowired
    AlipayService alipayService;

    @Autowired
    OrderRealMapper orderRealMapper;

    /**
     * 加入订单信息到redis中，并开始计时600秒后若无操作自动清除（前端展示）
     * fys 2022.8.2 11点46分
     * lzy 2022.8.15 20点01分
     * @param scenicTicketEntity
     * @return
     */
    @Override
    public Map<String, Object> saveScenicticket(ScenicOrderEntity scenicTicketEntity) throws AlipayApiException, ParseException {
        List<UserRealBindsEntity> expertResumeList = JSON.parseArray(scenicTicketEntity.getUserRealBinds(), UserRealBindsEntity.class);
        // 获取该订单售出几张门票
        Integer num = expertResumeList.toArray().length;
        // 生成订单号
        String code = RanNum.createRanNum();
        // 调用支付宝当面付调用precreate创建交易订单
        Map<String, Object> qecode = alipayService.qecode(scenicTicketEntity.getPrice(), code);
        // 支付宝当面付 创建订单 返回的二维码码串
        Object qrCode = qecode.get("QrCode");
        scenicTicketEntity.setQrCode((String) qrCode);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 需要加的分钟
        long amount = 5 * 60 * 1000;
        // 将订单失效时间 设置成10分钟
        String endTimeSdf = sdf.format(date.getTime() + amount);
        Date endTime = sdf.parse(endTimeSdf);
        scenicTicketEntity.setOrderNo(code);
        scenicTicketEntity.setOrderStatus(5);
        scenicTicketEntity.setPurchaseTime(new Date());
        scenicTicketEntity.setEndTime(endTime);
        scenicTicketEntity.setTicketNum(num);
        //为实体类set进入各种信息，并将code加入redis进行缓存，为期600秒
        redisUtil.set(code,scenicTicketEntity,600);
        //接收前端传入scenicId 并加入redis缓存 预留时间要略微高于code
        Integer scenicId = scenicTicketEntity.getScenicId();
        redisUtil.set("id",scenicId,630);
        //将实体类中的信息加入数据库，生成信息
        Integer i = purchaseMapper.insert(scenicTicketEntity);
        Integer orderId = scenicTicketEntity.getId();
        OrderRealEntity orderRealEntity = new OrderRealEntity();
        orderRealEntity.setSOId(orderId);
        for (UserRealBindsEntity userRealBindsEntity : expertResumeList) {
            orderRealEntity.setURId(userRealBindsEntity.getId());
            // 将订单主键与实名信息主键 存入 两表的关联表
            orderRealMapper.insert(orderRealEntity);
        }
        //购买成功减少门票 1 张
        ticketMapper.UpdateTicketsde(scenicTicketEntity.getScenicId(),num);
        //返回code提供前端接收，用于其他功能
        qecode.put("scenicTicketEntity", scenicTicketEntity);
        return qecode;
    }

    /**
     * 订单付款，将redis中缓存的数据取出，并进行更改状态付款处理（前端展示）
     * fys 2022.8.2 11点46分
     * @param scenicTicketEntity
     * @return
     */
    @Override
    public Integer UpdateScenicticketStatus(ScenicOrderEntity scenicTicketEntity) {
//        ScenicOrderEntity scenicTicketEntity1 =  (ScenicOrderEntity)redisUtil.get("scenic");
//        Integer scenicticky = purchaseMapper.insert(scenicTicketEntity1);
        Integer id = purchaseMapper.UpdateScenicticketStatus(scenicTicketEntity);
        System.out.println(scenicTicketEntity);
        if(id>0){
            System.out.println("修改成功");
        }else{
            System.out.println("添加失败");
        }
        return id;
    }
    /**
     * 订单付款，更改状态付款处理（前端展示）
     * fys 2022.8.2 11点46分
     * @param scenicTicketEntity
     * @return
     */
    @Override
    public Integer UpdateScenicticketStatus1(ScenicOrderEntity scenicTicketEntity) {
//        ScenicOrderEntity scenicTicketEntity1 =  (ScenicOrderEntity)redisUtil.get(code);
//        Integer scenicticky = purchaseMapper.insert(scenicTicketEntity1);
        Integer id = purchaseMapper.UpdateScenicticketStatus1(scenicTicketEntity);
        System.out.println(scenicTicketEntity);
        if(id>0){
            System.out.println("修改成功");
        }else{
            System.out.println("添加失败");
        }
        return id;
    }

    /**
     * 询问订单状态（前端展示）
     * lzy 2022-8-16 09点41分
     * @param code
     * @return
     */
    @Override
    public CommonResult queryOrderStatus(String code) throws AlipayApiException {
        Map<String, Object> query = alipayService.query(code);
        if (query.get("tradeStatus").equals("TRADE_SUCCESS")) {
            redisUtil.setRemove(code);
            ScenicOrderEntity scenicOrderEntity = new ScenicOrderEntity();
            scenicOrderEntity.setOrderNo(code);
            scenicOrderEntity.setOrderStatus(2);
            purchaseMapper.updateByPrimaryKeySelective(scenicOrderEntity);
        } else {

        }
        return null;
    }

    /**
     * 询问订单状态是否呗支付（前台展示）
     * lzy 2022-8-22 21点02分
     * @param code
     * @return
     */
    @Override
    public CommonResult getOrderQuery(String code) throws AlipayApiException {
        Map<String, Object> query = alipayService.query(code);
        Object tradeStatus = query.get("tradeStatus");
        if (tradeStatus.equals("TRADE_SUCCESS")) {
            redisUtil.del(code);
            purchaseMapper.updateOrderStatus(code,1);
        }
        return CommonResult.ok(query);
    }
}
